import * as Vue from 'vue'
import * as VueRouter from 'vue-router'
import App from './App.vue'
import { routes } from './js/web-router.js'
import NProgress from 'nprogress';
import ElementPlus from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

import * as echarts from 'echarts';

import '@fortawesome/fontawesome-free/js/all'
import 'element-plus/dist/index.css'
import '@/css/index.css'
import 'nprogress/nprogress.css';
import '@fortawesome/fontawesome-free/css/all.css'
import { config } from "@/js/config.js";

const SESSION_TO_NAME = "to";
const SESSION_FROM_NAME = "from";
const PROJECT_ROOT_NAME = config.projectRootName;

NProgress.configure({
    easing: 'ease',  // 动画方式
    speed: 500,  // 递增进度条的速度
    showSpinner: false, // 是否显示加载ico
    trickleSpeed: 200, // 自动递增间隔
    minimum: 0.3 // 初始化时的最小百分比
});

const app = Vue.createApp(App);

const router = VueRouter.createRouter({
    history: VueRouter.createWebHistory(PROJECT_ROOT_NAME),
    routes, 
});
//显示内容加载的进度条
router.beforeEach((to, from, next) => {
    NProgress.start();
    if (to.matched.length == 0) {
        next("/error?code=404");
    } else {
        //记录当前的路径
        localStorage.setItem(SESSION_TO_NAME, to.fullPath);
        localStorage.setItem(SESSION_FROM_NAME, from.fullPath);
        //拦截登录，有用户信息则直接跳转首页
        let isLogin = checkLocalLogin();
        if(to.meta.requiresAuth){
            //需要登录信息
            if(isLogin){
                next();
            }else{
                next("/");
            }
        }else{
            //不需要登录信息
            if(to.path == "/"){
                //如果登录则不显示登录页
                if (isLogin) {
                    next("/mainView");
                }else{
                    next();
                }
            }else{
                next();
            }
        }
    }
});

/**
 * 判断是否存储了用户信息
 * 
 * @author zhouhui
 * @since 1.0.0
 */
function checkLocalLogin () {
    const storteUserId = localStorage.getItem("userId");
    const token = localStorage.getItem("token");
    const user = localStorage.getItem("user");
    return Boolean(storteUserId && token && user);
}

router.afterEach(() => {
    NProgress.done();
});
app.use(router);

app.use(ElementPlus,{
    locale: zhCn,
});

for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}

app.config.globalProperties.$echarts = echarts;

app.mount('#app');

export default app;
